<template>
  <view class="wrap">
    <u-collapse
      :head-style="headStyle"
      v-if="roleId === 3"
      :body-style="bodyStyle"
    >
      <u-collapse-item
        :title="'队伍   ' + item.name"
        v-for="(item, index) in list"
        :key="index"
      >
        <u-cell-item title="队伍ID" :value="item.id"></u-cell-item>
        <u-cell-item title="队伍名称" :value="item.name"></u-cell-item>
        <u-cell-item title="队伍头像">
          <image
            :src="item.logo"
            mode="aspectFill"
            style="height: 100rpx; width: 100rpx"
          />
        </u-cell-item>
        <u-cell-item title="创建时间" :value="item.createTime"></u-cell-item>
        <u-cell-item title="球队经理" :value="item.manager"></u-cell-item>
        <u-cell-item title="球队口号" :value="item.slogan"></u-cell-item>
        <u-cell-item title="获胜次数" :value="item.winNum"></u-cell-item>
        <u-cell-item
          v-if="item.coachinfo.name === null"
          title="教练"
          :arrow="false"
        >
          <u-button
            slot="right-icon"
            type="error"
            shape="circle"
            size="mini"
            @click="showAddCoach(item)"
          >
            <u-icon name="plus"></u-icon>
          </u-button>
        </u-cell-item>
        <u-cell-item
          v-if="item.coachinfo.name !== null"
          title="教练"
          :value="item.coachinfo.name"
          :arrow="false"
        >
          <u-button
            slot="right-icon"
            type="error"
            shape="circle"
            size="mini"
            @click="showDeleteCoach(item.id)"
            style="margin-left: 10rpx"
          >
            <u-icon name="minus"></u-icon>
          </u-button>
        </u-cell-item>
        <u-collapse>
          <u-collapse-item title="球员信息">
            <u-cell-item :arrow="false">
              <u-button type="error" size="medium" @click="showAddPlayer(item)">
                <u-icon name="plus-circle-fill"></u-icon>
                添加球员
              </u-button>
            </u-cell-item>
            <u-cell-item
              v-for="(item2, index2) in item.playerinfos"
              :key="index2"
              :arrow="false"
              title="球员"
              :value="item2.name"
            >
              <u-button
                slot="right-icon"
                type="error"
                shape="circle"
                size="mini"
                @click="showDeletePlayer(item.id, item2.id)"
                style="margin-left: 10rpx"
              >
                <u-icon name="minus"></u-icon>
              </u-button>
            </u-cell-item>
          </u-collapse-item>
        </u-collapse>
        <view>
          <view class="btn">
            <u-button
              type="warning"
              shape="circle"
              plain
              @click="showUpdateTeam(item)"
              >修改</u-button
            >
          </view>
          <view class="btn">
            <u-button
              type="error"
              shape="circle"
              plain
              @click="showDeleteTeam(item.id)"
              >删除</u-button
            >
          </view>
        </view>
      </u-collapse-item>
    </u-collapse>
    <!-- 加载更多 -->
    <u-loadmore :status="status" @loadmore="load" v-if="roleId === 3" />
    <u-button type="success" @click="addTeamShow = true" v-if="roleId === 3"
      >添加球队</u-button
    >
    <!-- 登录用户为普通球员或者教练时 -->
    <view
      v-if="
        (roleId === 1 || roleId === 2) && Object.keys(currentTeam).length === 0
      "
      class="emptyTeam"
    >
      <u-empty text="还没有加入球队！！" mode="data" color="#f00" icon-color="#f00"></u-empty>
    </view>
    <view
      class="teamInfo"
      v-if="
        (roleId === 1 || roleId === 2) && Object.keys(currentTeam).length !== 0
      "
    >
      <!-- LOGO-->
      <u-avatar :src="currentTeam.logo" size="150" mode="square"></u-avatar>
      <!-- 信息 -->
      <view class="teamContent">
        <view>
          <text class="title">球队名称</text>
          <text>{{ currentTeam.name }}</text>
        </view>
        <view>
          <text class="title">创建时间</text>
          <text>{{ currentTeam.createTime }}</text>
        </view>
        <view>
          <text class="title">球队经理</text>
          <text>{{ currentTeam.manager }}</text>
        </view>
        <view>
          <text class="title">球队口号</text>
          <text>{{ currentTeam.slogan }}</text>
        </view>
        <view>
          <text class="title">球队所在地</text>
          <text>{{ currentTeam.location }}</text>
        </view>
        <view>
          <text class="title">获胜场数</text>
          <text>{{ currentTeam.winNum }}</text>
        </view>
        <view>
          <text class="title">球队教练</text>
          <text>{{ currentTeam.coachinfo.name }}</text>
        </view>
      </view>
    </view>
    <!-- 添加教练信息 -->
    <u-popup
      v-model="addCoachShow"
      mode="bottom"
      border-radius="10"
      closeable
      height="600"
    >
      <view class="addCoach">
        <view>
          <text>请选择教练</text>
          <u-select
            v-model="showCoachInfo"
            :list="coachInfoList"
            @confirm="selectCoachInfo"
          ></u-select>
          <view
            @click="showCoachInfo = true"
            style="
              height: 70rpx;
              width: 350rpx;
              border-bottom: 2rpx solid #82848a;
            "
            >{{ selectedCoach }}</view
          >
        </view>

        <u-button type="primary" shape="circle" @click="addCoach"
          >提交</u-button
        >
      </view>
    </u-popup>
    <!-- 删除教练信息 -->
    <u-popup v-model="deleteCoachShow" mode="top">
      <view>
        <text>是否删除？</text>
        <view class="btn">
          <u-button type="primary" plain @click="deleteCoach">是</u-button>
        </view>
        <view class="btn">
          <u-button type="error" plain @click="deleteCoachShow = false"
            >否</u-button
          >
        </view>
      </view>
    </u-popup>
    <!-- 添加球员信息 -->
    <u-popup v-model="addPlayerShow" mode="bottom" border-radius="10" closeable>
      <view class="addPlayerForm">
        <u-form
          :model="addPlayerForm"
          ref="addPlayerFormRef"
          :error-type="['message']"
        >
          <u-form-item
            label="添加球员"
            label-position="top"
            label-width="150rpx"
          >
            <u-checkbox
              @change="playerChange"
              v-model="item.checked"
              shape="circle"
              active-color="#19be6b"
              v-for="(item, index) in playerInfoList"
              :key="index"
              :name="item.id"
              >{{ item.name }}</u-checkbox
            >
          </u-form-item>
          <u-button
            type="primary"
            shape="circle"
            :ripple="true"
            @click="addPlayer"
            >提交</u-button
          >
        </u-form>
      </view>
    </u-popup>
    <!-- 删除球员信息 -->
    <u-popup v-model="deletePlayerShow" mode="top">
      <view>
        <text>是否删除？</text>
        <view class="btn">
          <u-button type="primary" plain @click="deletePlayer">是</u-button>
        </view>
        <view class="btn">
          <u-button type="error" plain @click="deletePlayerShow = false"
            >否</u-button
          >
        </view>
      </view>
    </u-popup>
    <!-- 添加球队信息 -->
    <u-popup v-model="addTeamShow" mode="bottom" border-radius="10" closeable>
      <view class="addTeamForm">
        <u-form
          :model="addTeamForm"
          ref="addTeamFormRef"
          :error-type="['message']"
        >
          <u-form-item label="姓名" prop="name" label-width="150rpx">
            <u-input v-model="addTeamForm.name"></u-input>
          </u-form-item>
          <u-form-item label="地址" prop="location" label-width="150rpx">
            <u-input v-model="addTeamForm.location"></u-input>
          </u-form-item>
          <u-form-item label="口号" prop="slogan" label-width="150rpx">
            <u-input v-model="addTeamForm.slogan"></u-input>
          </u-form-item>
          <u-form-item label="球队经理" prop="manager" label-width="150rpx">
            <u-input v-model="addTeamForm.manager"></u-input>
          </u-form-item>
          <u-form-item label="球队Logo" prop="logo" label-width="150rpx">
            <u-upload
              :action="action"
              :max-size="5 * 1024 * 1024"
              max-count="1"
              @on-success="avatarUpload"
            ></u-upload>
          </u-form-item>
          <u-button
            type="primary"
            shape="circle"
            :ripple="true"
            @click="addTeam"
            >提交</u-button
          >
        </u-form>
      </view>
    </u-popup>
    <!-- 修改球队信息 -->
    <u-popup
      v-model="updateTeamShow"
      mode="bottom"
      border-radius="10"
      closeable
    >
      <view class="updateTeamForm">
        <u-form
          :model="updateTeamForm"
          ref="updateTeamFormRef"
          :error-type="['message']"
        >
          <u-form-item label="姓名" label-width="150rpx">
            <u-input v-model="updateTeamForm.name"></u-input>
          </u-form-item>
          <u-form-item label="地址" label-width="150rpx">
            <u-input v-model="updateTeamForm.location"></u-input>
          </u-form-item>
          <u-form-item label="口号" label-width="150rpx">
            <u-input v-model="updateTeamForm.slogan"></u-input>
          </u-form-item>
          <u-form-item label="球队经理" label-width="150rpx">
            <u-input v-model="updateTeamForm.manager"></u-input>
          </u-form-item>
          <u-form-item label="球队Logo" label-width="150rpx">
            <u-upload
              :action="action"
              :max-size="5 * 1024 * 1024"
              max-count="1"
              @on-success="updateAvatarUpload"
            ></u-upload>
          </u-form-item>
          <u-button
            type="primary"
            shape="circle"
            :ripple="true"
            @click="updateTeam"
            >提交</u-button
          >
        </u-form>
      </view>
    </u-popup>
    <!-- 删除球队信息 -->
    <u-popup v-model="deleteTeamShow" mode="top">
      <view>
        <text>是否删除？</text>
        <view class="btn">
          <u-button type="primary" plain @click="deleteTeam">是</u-button>
        </view>
        <view class="btn">
          <u-button type="error" plain @click="deleteTeamShow = false"
            >否</u-button
          >
        </view>
      </view>
    </u-popup>
    <u-toast ref="teamToastRef" />
  </view>
</template>

<script>
export default {
  data() {
    return {
      roleId: -1,
      currentPage: 1,
      size: 10000,
      total: -1,
      headStyle: {
        fontWeight: "800",
        fontSize: "30rpx",
        height: "100rpx",
      },
      bodyStyle: {
        height: "100%",
        overflow: "scroll",
      },
      status: "loadmore",
      list: [],
      // 存放当前用户所在球队信息
      currentTeam: {},
      coachInfoList: [],
      playerInfoList: [],
      addTeamShow: false,
      addCoachShow: false,
      showCoachInfo: false,
      deleteCoachShow: false,
      addPlayerShow: false,
      deletePlayerShow: false,
      addCoachForm: {
        tid: "",
        cid: "",
      },
      addPlayerForm: {
        playerinfoList: [],
        tid: "",
      },
      // 选择教练名称
      selectedCoach: "",
      addTeamForm: {
        name: "",
        logo: "",
        manager: "",
        slogan: "",
        location: "",
      },
      addTeamFormRule: {
        name: [
          { required: true, message: "球队名称不能为空", trigger: "change" },
        ],
        logo: [
          { required: true, message: "球队Logo不能为空", trigger: "change" },
        ],
        manager: [
          { required: true, message: "球队经理不能为空", trigger: "change" },
        ],
        slogan: [
          { required: true, message: "球队口号不能为空", trigger: "change" },
        ],
        location: [
          { required: true, message: "球队地址不能为空", trigger: "change" },
        ],
      },
      updateTeamForm: {
        id: "",
        name: "",
        logo: "",
        manager: "",
        slogan: "",
        location: "",
      },
      deletePlayerForm: {
        tid: "",
        pid: "",
      },
      teamId: 0,
      updateTeamShow: false,
      deleteTeamShow: false,
      action: "http://basketballManage.mooncode.cn/upload/",
      updateTeamForm: {
        id: "",
        name: "",
        manager: "",
        slogan: "",
        location: "",
        logo: "",
      },
    };
  },
  methods: {
    // 获取所有球队信息
    async getAllTeams(currentPage, size) {
      const { data } = await this.$request({
        url: "/team/",
        data: {
          currentPage,
          size,
        },
      });
      this.total = data.total;
      if (this.total === 0) {
        this.status = "nomore";
      }
      let len = this.list.length;
      if (len < this.total) {
        data.data.forEach((item) => {
          this.list.push(item);
        });
        // 当球队中存在多个球员信息时，每一个球员都会使得total+1
        // 首先判断data中数组长度与list数组长度是否相同，相同则代表全部获取成功
        if (this.list.length === data.data.length) {
          this.status = "nomore";
        }
      }
    },

    // 获取当前用户对应球队信息
    async getCurrentTeam() {
      const { data } = await this.$request({
        url: "/team/currentTeam",
        data: {
          rid: this.roleId, 
        },
      });
      console.log(this.roleId);
      if (data.code !== 500 && data) {
        this.currentTeam = data;
      }
    },

    // 添加球队信息
    addTeam() {
      this.$refs.addTeamFormRef.validate(async (valid) => {
        if (valid) {
          const { data } = await this.$request({
            url: "/team/",
            method: "post",
            data: this.addTeamForm,
          });
          if (data.code === 200) {
            this.addTeamShow = false;
            return uni.reLaunch({
              url: "/pages/team/index",
            });
          } else {
            return this.$refs.teamToastRef.show({
              title: data.message,
              type: "error",
            });
          }
        } else {
          return this.$refs.teamToastRef.show({
            title: "输入不合法，请重新输入！",
            type: "error",
          });
        }
      });
    },

    // 点击加载更多数据
    load() {
      if (this.currentPage >= this.total) return;
      this.status = "loading";
      this.currentPage = ++this.currentPage;
      setTimeout(() => {
        this.getAllTeams(this.currentPage, this.size);
        if (this.currentPage >= this.total) this.status = "nomore";
        else this.status = "loadmore";
      }, 2000);
    },

    // 显示添加教练
    async showAddCoach(item) {
      this.addCoachForm.tid = item.id;
      this.addCoachShow = true;
      const { data } = await this.$request({
        url: "/coachinfo/",
      });
      data.data.forEach((item) => {
        let obj = {};
        obj.label = item.name;
        obj.value = item.id;
        this.coachInfoList.push(obj);
      });
    },

    // 选择教练
    selectCoachInfo(e) {
      this.addCoachForm.cid = e[0].value;
      this.selectedCoach = e[0].label;
    },

    // 添加教练
    async addCoach() {
      const { data } = await this.$request({
        url: "/team/coachInfo",
        method: "post",
        data: this.addCoachForm,
        contentType: "application/x-www-form-urlencoded",
      });
      if (data.code === 200) {
        this.addCoachShow = false;
        return uni.reLaunch({
          url: "/pages/team/index",
        });
      } else {
        return this.$refs.teamToastRef.show({
          title: data.message,
          type: "error",
        });
      }
    },

    // 显示删除教练
    showDeleteCoach(id) {
      this.deleteCoachShow = true;
      this.addCoachForm.tid = id;
    },

    // 删除教练
    async deleteCoach() {
      const { data } = await this.$request({
        url: "/team/deleteCoach",
        method: "post",
        data: {
          id: this.addCoachForm.tid,
        },
      });
      if (data.code === 200) {
        this.deleteCoachShow = false;
        return uni.reLaunch({
          url: "/pages/team/index",
        });
      } else {
        return this.$refs.teamToastRef.show({
          title: data.message,
          type: "error",
        });
      }
    },

    // 显示添加球员
    async showAddPlayer(item) {
      this.addPlayerShow = true;
      this.addPlayerForm.tid = item.id;
      const { data } = await this.$request({
        url: "/playerinfo/",
        data: {
          currentPage: this.currentPage,
          size: this.size,
        },
      });
      data.data.forEach((item2) => {
        let obj = {};
        obj.id = item2.id;
        obj.name = item2.name;
        obj.checked = false;
        obj.disabled = false;
        this.playerInfoList.push(obj);
      });
    },

    // 选中球员
    playerChange(e) {
      if (e.value) {
        this.addPlayerForm.playerinfoList.push({
          id: e.name,
        });
      } else {
        // 删除数组中对应的元素
        this.removeByValue(this.addPlayerForm.playerinfoList, "id", e.name);
      }
    },

    // 添加球员信息
    async addPlayer() {
      const { data } = await this.$request({
        url: "/team/playerInfo",
        method: "post",
        data: this.addPlayerForm,
      });
      if (data.code === 200) {
        this.showAddPlayer = false;
        return uni.reLaunch({
          url: "/pages/team/index",
        });
      } else {
        return this.$refs.teamToastRef.show({
          title: data.message,
          type: "error",
        });
      }
    },

    // 显示删除球员信息
    showDeletePlayer(tid, pid) {
      this.deletePlayerShow = true;
      this.deletePlayerForm.pid = pid;
      this.deletePlayerForm.tid = tid;
    },

    // 删除球员信息
    async deletePlayer() {
      const { data } = await this.$request({
        url: "/team/deletePlayer",
        method: "post",
        contentType: "application/x-www-form-urlencoded",
        data: this.deletePlayerForm,
      });
      if (data.code === 200) {
        this.deletePlayerShow = false;
        return uni.reLaunch({
          url: "/pages/team/index",
        });
      } else {
        return this.$refs.teamToastRef.show({
          title: data.message,
          type: "error",
        });
      }
    },

    // 显示修改球队信息
    showUpdateTeam(item) {
      this.updateTeamShow = true;
      this.updateTeamForm.id = item.id;
      this.updateTeamForm.name = item.name;
      this.updateTeamForm.logo = item.logo;
      this.updateTeamForm.manager = item.manager;
      this.updateTeamForm.slogan = item.slogan;
      this.updateTeamForm.location = item.location;
    },

    // 修改球队信息
    async updateTeam() {
      const { data } = await this.$request({
        url: "/team/",
        method: "put",
        data: this.updateTeamForm,
      });
      if (data.code === 200) {
        this.updateTeamShow = false;
        return uni.reLaunch({
          url: "/pages/team/index",
        });
      } else {
        return this.$refs.teamToastRef.show({
          title: data.message,
          type: "error",
        });
      }
    },

    // 显示删除球队信息
    showDeleteTeam(id) {
      this.deleteTeamShow = true;
      this.teamId = id;
    },

    // 删除球队信息
    async deleteTeam() {
      const { data } = await this.$request({
        url: `/team/${this.teamId}`,
        method: "delete",
      });
      if (data.code === 200) {
        this.showDeleteTeam = false;
        return uni.reLaunch({
          url: "/pages/team/index",
        });
      } else {
        return this.$refs.teamToastRef.show({
          title: data.message,
          type: "error",
        });
      }
    },

    // 当上传头像后触发
    avatarUpload(data) {
      this.addTeamForm.logo = data.object.avatarUrl;
    },

    updateAvatarUpload(data) {
      this.updateTeamForm.logo = data.object.avatarUrl;
    },
  },
  onLoad() {
    // 获取当前用户角色，判断角色类型
    this.roleId = uni.getStorageSync("userInfo").roleid;
    
    this.getAllTeams(this.currentPage, this.size);
    this.getCurrentTeam();
  },

  onReady() {
    this.$refs.addTeamFormRef.setRules(this.addTeamFormRule);
  },
};
</script>

<style scoped lang="scss">
.wrap {
  width: 100vw;
  height: 100vh;
  padding: 15rpx 30rpx;


  .emptyTeam {
    margin-top: 50%;
  }

  .teamInfo {
    position: relative;
    u-avatar {
      z-index: 1;
      position: absolute;
      top: 10rpx;
      left: 50%;
      transform: translateX(-50%);
    }

    .teamContent {
      position: relative;
      top: 180rpx;
      width: 100%;
      view {
        display: flex;
        padding: 10rpx 20rpx;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10rpx;
        border-bottom: 2rpx solid #ccc;
        .title {
          font-weight: 800;
        }
        text {
          height: 50rpx;
        }
      }
    }
  }

  .btn {
    width: 50%;
    margin-top: 15rpx;
    margin-left: auto;
    margin-right: auto;
  }

  .addTeamForm,
  .updateTeamForm,
  .addPlayerForm {
    padding: 15rpx 30rpx;
  }

  .addCoach {
    padding: 20rpx 45rpx;

    view {
      display: flex;
      align-items: center;
      margin: 20rpx auto;
    }
  }

  u-popup {
    view {
      padding: 10rpx 30rpx;

      text {
        font-weight: 800;
        font-size: 35rpx;
        margin-bottom: 20rpx;
      }
    }
  }
}


</style>